package com.coder.bike.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.coder.bike.entity.Customer;
import com.coder.bike.entity.Staff;
import com.coder.bike.security.CustomerUserDetailsService;
import com.coder.bike.service.IStaffService;
import com.coder.bike.utils.RedisUtils;
import com.coder.bike.utils.Result;
import com.coder.bike.vo.StaffRegisterDTO;
import jakarta.annotation.Resource;
import lombok.Data;
import org.springframework.web.bind.annotation.*;

;import java.util.List;
import java.util.Objects;

import static com.coder.bike.utils.LoginUtil.authenticateUser;
import static com.coder.bike.utils.LoginUtil.verifySmsCode;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 沈诩宸
 * @since 2025-04-22
 */
@RestController
@RequestMapping("/bike/staff")
public class StaffController {
    @Resource
    private IStaffService iStaffService;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private CustomerUserDetailsService customerUserDetailsService;

    @GetMapping
    public List<Staff> getStaff() {
        return iStaffService.list();
    }

    @PostMapping("{start}/{size}")
    public Result search(@PathVariable int start, @PathVariable int size,
                         @RequestBody Staff user) {
        return Result.success(iStaffService.searchByPage(new Page<>(start, size),
                user));
    }

    @PostMapping
    public Result save(@RequestBody Staff user) {
        Staff user1 = iStaffService.selectByUsername(user.getUsername());
        if (user1 != null) {
            return Result.fail().setMessage("用户名已存在");
        } else {
            user.setPassword(user.getPassword());
            user.setIsAdmin(false);
            if (StrUtil.isEmpty(user.getAvatar())) {
                user.setAvatar("http://gips3.baidu.com/it/u=1537137094,335954266&fm=3028&app=3028&f=JPEG&fmt=auto?w=720&h=1280");
            }
            return iStaffService.save(user) ? Result.success() :
                    Result.fail();
        }
    }

    @PutMapping
    public Result update(@RequestBody Staff user) {
        Staff u = iStaffService.selectByUsername(user.getUsername());
        if (u != null && !Objects.equals(u.getId(), user.getId())) {
            return Result.fail().setMessage("用户名已存在");
        }
        if (StrUtil.isEmpty(user.getAvatar())) {
            user.setAvatar("http://gips3.baidu.com/it/u=1537137094,335954266&fm=3028&app=3028&f=JPEG&fmt=auto?w=720&h=1280");
        }
        return iStaffService.updateById(user) ? Result.success() :
                Result.fail();
    }
    @GetMapping("getById/{id}")
    public Result getById(@PathVariable Integer id) {
        try {
            Staff staff = iStaffService.getById(id);
            if (staff != null) {
                return Result.success(staff);
            } else {
                return Result.fail().setMessage("不存在此员工");
            }
        } catch (Exception e) {
            return Result.fail().setMessage("获取员工信息失败: " + e.getMessage());
        }
    }

    @PostMapping("registerByPhone")
    public Result registerByPhone(@RequestBody StaffRegisterDTO dto) {
        // 验证短信验证码
        Result verifyResult = verifySmsCode(redisUtils, dto.getPhone(), "register", dto.getCode());
        if (!verifyResult.getSuccess()) {
            return verifyResult;
        }

        // 检查手机号是否已注册
        Staff existingStaff = iStaffService.selectByPhone(dto.getPhone());
        if (existingStaff != null) {
            return Result.fail().setMessage("该手机号已注册");
        }

        Staff staff = getStaff(dto);

        if (iStaffService.save(staff)) {
            return authenticateUser(redisUtils, customerUserDetailsService, staff.getUsername(), staff.getPassword(), "STAFF");
        }
        return Result.fail();
    }

    private static Staff getStaff(StaffRegisterDTO dto) {
        Staff staff = new Staff();
        staff.setPhone(dto.getPhone());
        staff.setUsername(dto.getPhone());
        staff.setPassword(dto.getPassword());
        staff.setRealname(dto.getRealname() != null ? dto.getRealname() : "员工" + dto.getPhone().substring(7));
        staff.setIsAdmin(false);
        if (dto.getAvatar() == null || dto.getAvatar().isEmpty()) {
            staff.setAvatar("http://gips3.baidu.com/it/u=1537137094,335954266&fm=3028&app=3028&f=JPEG&fmt=auto?w=720&h=1280");
        } else {
            staff.setAvatar(dto.getAvatar());
        }
        return staff;
    }


}
